// src/pages/FoodPage.tsx
import React, { useState, useEffect } from 'react';
import { 
  IonPage, 
  IonHeader, 
  IonToolbar, 
  IonTitle, 
  IonContent, 
  IonGrid, 
  IonRow, 
  IonCol,
  IonSearchbar,
  IonList,
  IonItem,
  IonLabel,
  IonIcon,
  IonCard,
  IonCardHeader,
  IonCardTitle,
  IonCardContent,
  IonImg,
  IonChip,
  IonButton,
  IonButtons,
  IonMenuButton
} from '@ionic/react';
import { 
  pizza, 
  fastFood, 
  wine, 
  iceCream, 
  cafe, 
  fish, 
  nutrition, 
  restaurant,
  star,
  heart,
  cart,
  filter
} from 'ionicons/icons';
import './FoodPage.css';

// 定义食物分类类型
interface FoodCategory {
  id: number;
  name: string;
  icon: string;
}

// 定义食物类型
interface FoodItem {
  id: number;
  name: string;
  description: string;
  price: number;
  categoryId: number;
  image: string;
  rating: number;
  favorite: boolean;
}

const FoodPage2: React.FC = () => {
  const [selectedCategory, setSelectedCategory] = useState<number>(1);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [filteredFoods, setFilteredFoods] = useState<FoodItem[]>([]);
  const [isMobile, setIsMobile] = useState<boolean>(false);
  const [showCategories, setShowCategories] = useState<boolean>(false);

  // 食物分类数据
  const foodCategories: FoodCategory[] = [
    { id: 1, name: '披萨', icon: pizza },
    { id: 2, name: '快餐', icon: fastFood },
    { id: 3, name: '饮品', icon: wine },
    { id: 4, name: '甜点', icon: iceCream },
    { id: 5, name: '咖啡', icon: cafe },
    { id: 6, name: '海鲜', icon: fish },
    { id: 7, name: '健康餐', icon: nutrition },
    { id: 8, name: '中餐', icon: restaurant }
  ];

  // 食物数据
  const foodItems: FoodItem[] = [
    { id: 1, name: '意大利香肠披萨', description: '经典意大利风味，配以香肠和芝士', price: 89, categoryId: 1, image: 'pizza.jpg', rating: 4.8, favorite: true },
    { id: 2, name: '夏威夷披萨', description: '火腿和菠萝的完美组合', price: 85, categoryId: 1, image: 'pizza2.jpg', rating: 4.5, favorite: false },
    { id: 3, name: '双层芝士汉堡', description: '双层牛肉饼配特制酱料', price: 45, categoryId: 2, image: 'burger.jpg', rating: 4.7, favorite: true },
    { id: 4, name: '炸鸡套餐', description: '酥脆炸鸡配薯条和可乐', price: 58, categoryId: 2, image: 'chicken.jpg', rating: 4.3, favorite: false },
    { id: 5, name: '鲜榨橙汁', description: '新鲜橙子现榨', price: 25, categoryId: 3, image: 'juice.jpg', rating: 4.6, favorite: false },
    { id: 6, name: '草莓奶昔', description: '新鲜草莓与牛奶的完美融合', price: 32, categoryId: 3, image: 'milkshake.jpg', rating: 4.9, favorite: true },
    { id: 7, name: '巧克力蛋糕', description: '浓郁巧克力风味', price: 38, categoryId: 4, image: 'cake.jpg', rating: 4.8, favorite: true },
    { id: 8, name: '草莓冰淇淋', description: '新鲜草莓制作', price: 28, categoryId: 4, image: 'icecream.jpg', rating: 4.4, favorite: false },
    { id: 9, name: '拿铁咖啡', description: '意式浓缩咖啡与牛奶', price: 32, categoryId: 5, image: 'latte.jpg', rating: 4.7, favorite: false },
    { id: 10, name: '卡布奇诺', description: '经典意式咖啡', price: 35, categoryId: 5, image: 'cappuccino.jpg', rating: 4.5, favorite: false },
    { id: 11, name: '清蒸鲈鱼', description: '新鲜鲈鱼清蒸', price: 128, categoryId: 6, image: 'fish.jpg', rating: 4.9, favorite: true },
    { id: 12, name: '蒜蓉大虾', description: '新鲜大虾配蒜蓉酱', price: 98, categoryId: 6, image: 'shrimp.jpg', rating: 4.6, favorite: false },
    { id: 13, name: '蔬菜沙拉', description: '新鲜时蔬配特制酱料', price: 38, categoryId: 7, image: 'salad.jpg', rating: 4.2, favorite: false },
    { id: 14, name: '鸡胸肉配糙米', description: '低脂健康餐', price: 48, categoryId: 7, image: 'chicken_breast.jpg', rating: 4.3, favorite: false },
    { id: 15, name: '宫保鸡丁', description: '经典川菜', price: 58, categoryId: 8, image: 'kungpao.jpg', rating: 4.8, favorite: true },
    { id: 16, name: '麻婆豆腐', description: '麻辣鲜香', price: 42, categoryId: 8, image: 'tofu.jpg', rating: 4.7, favorite: false }
  ];

  // 检测屏幕尺寸
  useEffect(() => {
    const checkScreenSize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    // 初始检查
    checkScreenSize();
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', checkScreenSize);
    
    // 清理函数
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  // 过滤食物
  useEffect(() => {
    let result = foodItems;
    
    // 按分类过滤
    if (selectedCategory !== 0) {
      result = result.filter(food => food.categoryId === selectedCategory);
    }
    
    // 按搜索词过滤
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(food => 
        food.name.toLowerCase().includes(term) || 
        food.description.toLowerCase().includes(term)
      );
    }
    
    setFilteredFoods(result);
  }, [selectedCategory, searchTerm]);

  // 切换收藏状态
  const toggleFavorite = (id: number) => {
    const updatedFoods = foodItems.map(food => 
      food.id === id ? { ...food, favorite: !food.favorite } : food
    );
    setFilteredFoods(updatedFoods.filter(food => 
      (selectedCategory === 0 || food.categoryId === selectedCategory) &&
      (searchTerm === '' || 
        food.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
        food.description.toLowerCase().includes(searchTerm.toLowerCase()))
    ));
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar color="primary">
          {isMobile && (
            <IonButtons slot="start">
              <IonMenuButton onClick={() => setShowCategories(!showCategories)} />
            </IonButtons>
          )}
          <IonTitle>美食发现</IonTitle>
          <IonButtons slot="end">
            <IonButton>
              <IonIcon slot="icon-only" icon={cart} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
        
        {/* 搜索栏 */}
        <IonToolbar>
          <IonSearchbar 
            value={searchTerm}
            onIonChange={e => setSearchTerm(e.detail.value!)}
            placeholder="搜索美食..."
            animated
          />
          {isMobile && (
            <IonButtons slot="end">
              <IonButton onClick={() => setShowCategories(!showCategories)}>
                <IonIcon slot="icon-only" icon={filter} />
              </IonButton>
            </IonButtons>
          )}
        </IonToolbar>
      </IonHeader>
      
      <IonContent>
        <IonGrid className="food-page-grid">
          <IonRow>
            {/* 桌面端侧边栏 */}
            {!isMobile && (
              <IonCol size="3" className="sidebar-col">
                <div className="sidebar-header">
                  <h2>美食分类</h2>
                </div>
                <IonList className="category-list">
                  <IonItem 
                    className={`category-item ${selectedCategory === 0 ? 'active' : ''}`}
                    onClick={() => setSelectedCategory(0)}
                  >
                    <IonLabel>全部美食</IonLabel>
                  </IonItem>
                  {foodCategories.map(category => (
                    <IonItem 
                      key={category.id}
                      className={`category-item ${selectedCategory === category.id ? 'active' : ''}`}
                      onClick={() => setSelectedCategory(category.id)}
                    >
                      <IonIcon slot="start" icon={category.icon} />
                      <IonLabel>{category.name}</IonLabel>
                    </IonItem>
                  ))}
                </IonList>
              </IonCol>
            )}
            
            {/* 主内容区域 */}
            <IonCol className="content-col">
              {/* 移动端分类菜单 */}
              {isMobile && showCategories && (
                <div className="mobile-categories">
                  <IonList className="category-list">
                    <IonItem 
                      className={`category-item ${selectedCategory === 0 ? 'active' : ''}`}
                      onClick={() => {
                        setSelectedCategory(0);
                        setShowCategories(false);
                      }}
                    >
                      <IonLabel>全部美食</IonLabel>
                    </IonItem>
                    {foodCategories.map(category => (
                      <IonItem 
                        key={category.id}
                        className={`category-item ${selectedCategory === category.id ? 'active' : ''}`}
                        onClick={() => {
                          setSelectedCategory(category.id);
                          setShowCategories(false);
                        }}
                      >
                        <IonIcon slot="start" icon={category.icon} />
                        <IonLabel>{category.name}</IonLabel>
                      </IonItem>
                    ))}
                  </IonList>
                </div>
              )}
              
              {/* 内容标题 */}
              <div className="content-header">
                <h1>
                  {selectedCategory === 0 
                    ? '所有美食' 
                    : foodCategories.find(c => c.id === selectedCategory)?.name}
                </h1>
                <p>共 {filteredFoods.length} 种美食</p>
              </div>
              
              {/* 美食网格 */}
              {filteredFoods.length > 0 ? (
                <div className="food-grid">
                  {filteredFoods.map(food => (
                    <IonCard key={food.id} className="food-card">
                      <div className="food-image-container">
                        <IonImg 
                          src={`https://picsum.photos/seed/${food.id}/300/200`} 
                          alt={food.name}
                          className="food-image"
                        />
                        <IonButton 
                          className="favorite-button"
                          fill="clear"
                          onClick={() => toggleFavorite(food.id)}
                        >
                          <IonIcon 
                            icon={heart} 
                            color={food.favorite ? "danger" : "medium"} 
                          />
                        </IonButton>
                      </div>
                      <IonCardHeader>
                        <IonCardTitle>{food.name}</IonCardTitle>
                      </IonCardHeader>
                      <IonCardContent>
                        <p className="food-description">{food.description}</p>
                        <div className="food-footer">
                          <IonChip color="primary">
                            <IonIcon icon={star} />
                            <IonLabel>{food.rating}</IonLabel>
                          </IonChip>
                          <p className="price">¥{food.price.toFixed(2)}</p>
                        </div>
                        <IonButton expand="block" color="primary">
                          加入购物车
                        </IonButton>
                      </IonCardContent>
                    </IonCard>
                  ))}
                </div>
              ) : (
                <div className="no-results">
                  <h2>没有找到相关美食</h2>
                  <p>请尝试其他分类或搜索词</p>
                </div>
              )}
            </IonCol>
          </IonRow>
        </IonGrid>
      </IonContent>
    </IonPage>
  );
};

export default FoodPage2;